const express = require("express");
const router = express.Router();
const { User } = require("../models");
const { success, failure } = require("../utils/response");
const {
  BadRequest,
  NotFound,
  Unauthorized,
} = require('http-errors');
const bcrypt = require("bcryptjs");

/**
 * 查询当前登录用户详情
 * GET /users/me
 */
router.get("/me", async function (req, res) {
  try {
    const user = await getUser(req);
    success(res, "查询当前用户信息成功。", { user });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 公共方法：查询当前用户
 * @param req
 * @param showPassword
 * @returns {Promise<Model<any, TModelAttributes>>}
 */
async function getUser(req, showPassword = false) {
  const id = req.userId;

  let condition = {};
  if (!showPassword) {
    condition = {
      attributes: { exclude: ["password"] },
    };
  }

  const user = await User.findByPk(id, condition);
  if (!user) {
    throw new NotFound(`ID: ${id}的用户未找到。`);
  }

  return user;
}

/**
 * 更新用户信息
 * PUT /users/info
 */
router.put("/info", async function (req, res) {
  try {
    const body = {
      nickname: req.body.nickname,
      sex: req.body.sex,
      company: req.body.company,
      introduce: req.body.introduce,
      avatar: req.body.avatar,
    };

    const user = await getUser(req);
    await user.update(body);
    success(res, "更新用户信息成功。", { user });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 更新账户信息
 * PUT /users/account
 */
router.put("/account", async (req, res) => {
  try {
    // 获取body数据
    const { email, username, currentPassword, password, confirmPassword } =
      req.body;
    const body = {
      email,
      username,
      currentPassword,
      password,
      confirmPassword,
    };
    // 验证当前密码是否填写，在验证两次密码是否一致
    if (!currentPassword) {
      throw new BadRequest("请输入当前用户密码");
    }
    if (password != confirmPassword) {
      throw new BadRequest("两次密码要输入一致");
    }
    // 查询当前用户
    const user = await getUser(req, true);
    // 验证单签密码是否正确
    const flag = bcrypt.compareSync(currentPassword, user.password);
    if (!flag) {
      throw new Unauthorized("用户当前密码不正确");
    }
    // 更新当前用户信息
    await user.update(body);
    // 删除密码
    delete user.dataValues.password;
    // 返回结果
    success(res, "账号更新成功", { user });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
